package me.rocky.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.result.condition.ProducesRequestCondition;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author Rocky
 * @version 1.0
 * @description
 * @email inaho00@foxmail.com
 * @createDate 2021/9/18 下午12:20
 * @log
 */
@Slf4j
@RestController
public class TestController {

	@Autowired
	private ReactiveRedisTemplate<String,String> reactiveRedisTemplate;

	@GetMapping("/add")
	@PreAuthorize("hasAnyRole('admin')")
	public Mono<?> add(String v){
		Mono<Boolean> v1 = reactiveRedisTemplate.opsForValue().set("v", v);
		return v1;
	}

	@GetMapping("/get")
	public Mono<?> get(){
		Mono<String> v1 = reactiveRedisTemplate.opsForValue().get("v");
		return v1;
	}

	@GetMapping("/normal")
	public String normal(){
		log.info("start: {}",System.currentTimeMillis());
		String s = getStr();
		log.info("end: {}",System.currentTimeMillis());
		return s;
	}

	@GetMapping("/mono")
	public Mono<String> mono(){
		log.info("start: {}",System.currentTimeMillis());
		Mono<String> res = Mono.fromSupplier(this::getStr);
		log.info("end: {}",System.currentTimeMillis());
		return res;
	}

	@GetMapping(value = "/flux",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
	public Flux<String> flux(){
		log.info("start: {}",System.currentTimeMillis());
		Flux<String> res = Flux.fromStream(IntStream.range(1,5).mapToObj(e->{
			try {
				TimeUnit.SECONDS.sleep(3L);
			} catch (InterruptedException interruptedException) {
				interruptedException.printStackTrace();
			}
			return e+"  flux";
		}));
		log.info("end: {}",System.currentTimeMillis());
		return res;
	}

	private String getStr(){
		try {
			TimeUnit.SECONDS.sleep(5);
		}catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "hello world";
	}
}
